<?php

require_once 'IDBHelper.php.inc';
require_once 'DBConfig.inc';

class PdoHelper implements IDBHelper {
	
	private static $instance;
	private $db;
	
	private function __construct() {
		
		switch (DBType) {
			case "pdo":
				$options = array();
				$options[PDO::MYSQL_ATTR_INIT_COMMAND] = "SET NAMES '".PDO_Charset."'";
				$options[PDO::ATTR_PERSISTENT] = true;
				$options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
				
				$this->db = new PDO(PDO_Engine.":host=".PDO_Server.";dbname=".PDO_DB, PDO_UserName, PDO_PassWord, $options);
				break;
		}
	}
	
	public static function CreateHelper() {
		if(!isset(PdoHelper::$instance)) {
			PdoHelper::$instance = new PdoHelper();
		}
		
		return PdoHelper::$instance;
	}

	/**
	 * 执行sql语句， 返回影响行数
	 */
	public function ExecuteNonQuery($sql, array $para = null) {

		if(empty($para)) {
			$stmt = $this->db->query($sql); // use query, not call execute
		} else {
			$stmt = $this->db->prepare($sql);
			$stmt->execute($para);
		}
		$cnt = $stmt->rowCount();
		
		return $cnt;
	}
	
	/**
	 * 执行sql查询，返回数组结果集
	 */
	public function ExecuteArray($sql, array $para = null) {
		
		if(empty($para)) {
			$stmt = $this->db->query($sql); // use query, not call execute
		} else {
			$stmt = $this->db->prepare($sql);
			$stmt->execute($para);
		}
		
		$rt = $stmt->fetchAll();
		
		$stmt->closeCursor();
		
		return $rt;
	}

	/**
	 * 执行sql查询，返回指定类型的数组结果集
	 */
	public function ExecuteObject($sql, $objectName, array $para = null) {
		
		if(empty($para)) {
			$stmt = $this->db->query($sql); // use query, not call execute
			$stmt->setFetchMode(PDO::FETCH_CLASS, $objectName);
		} else {
			$stmt = $this->db->prepare($sql);
			$stmt->setFetchMode(PDO::FETCH_CLASS, $objectName);
			$stmt->execute($para);
		}
		
		$rt = $stmt->fetchAll();
		
		$stmt->closeCursor();
		
		return $rt;
	}
	
	/**
	 * 执行sql查询，返回指定类型的单个数组结果
	 */
	public function ExecuteSingleObject($sql, $objectName, array $para = null) {

		if(empty($para)) {
			$stmt = $this->db->query($sql); // use query, not call execute
			$stmt->setFetchMode(PDO::FETCH_CLASS, $objectName);
		} else {
			$stmt = $this->db->prepare($sql);
			$stmt->setFetchMode(PDO::FETCH_CLASS, $objectName);
			$stmt->execute($para);
		}
		
		$rt = $stmt->fetch();
		
		$stmt->closeCursor();
		
		return $rt;
	}
	
	/**
	 * 执行sql查询，返回第一行第一列的值
	 */
	public function ExecuteScalar($sql, array $para = null) {

		if(empty($para)) {
			$stmt = $this->db->query($sql); // use query, not call execute
		} else {
			$stmt = $this->db->prepare($sql);
			$stmt->execute($para);
		}
		
		$row = $stmt->fetch();
		
		$rt = "";
		if(isset($row) && isset($row[0])) {
			$rt = $row[0];
		}
		
		$stmt->closeCursor();
		
		return $rt;
	}
	
}

?>